import 'package:flutter_admin/api/odoo/stores_requisition_odoo_api.dart';
import 'package:flutter_admin/models/odoo/stores_requisition.dart';
import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/cry_dialog.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/pages/odoo/material/stores_requisition/stores_requisition_detail.dart';
import 'package:flutter_admin/pages/odoo/material/stores_requisition/stores_requisition_dialog.dart';
import 'package:flutter_admin/pages/odoo/material/stores_requisition/stores_requisition_edit.dart';
import 'package:flutter_admin/pages/odoo/material/stores_requisition/stores_requisition_relation.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

class StoresRequisitionList extends StatefulWidget {
  StoresRequisitionList({Key? key}) : super(key: key);

  @override
  _StoresRequisitionListState createState() => _StoresRequisitionListState();
}

class _StoresRequisitionListState extends State<StoresRequisitionList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);

  StoresRequisition storesRequisition = StoresRequisition();

  DateFormat format = DateFormat('yyyy-MM-dd');
  //车间名称
  List<SelectOptionVO> workshopIdList = [];

  List<StoresRequisition> selectedList = [];
  @override
  void initState() {
    super.initState();
    _loadSelectVO();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  _loadSelectVO() async {
    UserInfo userInfo = StoreUtil.getCurrentUserInfo();
    // this.workshopIdList = await DynamicDataApi.getModelSelect(
    //     // active: false,
    //     model: "hr.department",
    //     name: "complete_name",
    //     key: 'parent_id',
    //     operator: "!=",
    //     val: null);
    storesRequisition.workshopId = userInfo.deptId;
    storesRequisition.workshopName = userInfo.deptName;
    storesRequisition.dateStart = Utils.getDate();
    storesRequisition.dateEnd = Utils.getDate();
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelectDate(
            context,
            width: 180,
            label: '领料开始日期',
            value: storesRequisition.dateStart,
            lastDate: isNotBlank(storesRequisition.dateEnd)
                ? format.parse(storesRequisition.dateEnd!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              storesRequisition.dateStart = v;
              setState(() {});
            },
            onSaved: (v) {
              storesRequisition.dateStart = v;
            },
          ),
          CrySelectDate(
            context,
            width: 180,
            label: '领料结束日期',
            value: storesRequisition.dateEnd,
            firstDate: isNotBlank(storesRequisition.dateStart)
                ? format.parse(storesRequisition.dateStart!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              storesRequisition.dateEnd = v;
              setState(() {});
            },
            onSaved: (v) {
              storesRequisition.dateEnd = v;
            },
          ),
          CryInput(
            width: 280,
            label: '生产车间',
            enable: false,
            value: storesRequisition.workshopName,
            onSaved: (v) {
              storesRequisition.workshopName = v;
            },
          ),
          // CrySelect(
          //   width: 280,
          //   label: '生产车间',
          //   enable: false,
          //   dataList: workshopIdList,
          //   value: storesRequisition.workshopId,
          //   onSaved: (v) => {storesRequisition.workshopId = v},
          //   onChange: (v) async {
          //     if (storesRequisition.workshopId != v) {
          //       formKey.currentState!.save();
          //       storesRequisition.workshopId = v;
          //       setState(() {});
          //     }
          //   },
          // )
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('领料单号')),
        DataColumn(label: Text('用途')),
        DataColumn(label: Text('车间')),
        DataColumn(label: Text('领料人')),
        DataColumn(label: Text('领料日期')),
      ],
      getCells: (m) {
        StoresRequisition storesRequisition = StoresRequisition.fromMap(m);
        return [
          DataCell(Text(storesRequisition.number ?? '--')),
          DataCell(Text(storesRequisition.purpose ?? '--')),
          DataCell(Text(storesRequisition.workshopName ?? '--')),
          DataCell(Text(storesRequisition.userName ?? '--')),
          DataCell(
              Text(storesRequisition.requisitionDate ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        CryButtons.add(context, () => _edit(null)),
        CryButtons.edit(context,
            selectedList.length != 1 ? null : () => _edit(selectedList[0])),
        CryButtons.delete(context,
            selectedList.length < 1 ? null : () => _delete(selectedList)),
        CryButton(
          label: "领料单绑定",
          iconData: Icons.view_headline,
          onPressed: selectedList.length == 1
              ? () => _openBind(selectedList[0])
              : null,
        ),
        CryButton(
          label: "领料单明细",
          iconData: Icons.view_headline,
          onPressed: selectedList.length == 1
              ? () => _openDetail(selectedList[0])
              : null,
        ),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          // isDisplayDesktop(context) ? form : Container(),
          // isDisplayDesktop(context) ? buttonBar : Container(),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: isDisplayDesktop(context) ? buttonBar : Container(),
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _openBind(StoresRequisition storesRequisition) {
    Utils.fullscreenDialog(
        StoresRequisitionRelation(storesRequisition: storesRequisition));
  }

  _openDetail(StoresRequisition storesRequisition) {
    Utils.fullscreenDialog(
        StoresRequisitionDetail(storesRequisition: storesRequisition));
  }

  _edit(StoresRequisition? storesRequisition) async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: StoresRequisitionEdit(
          storesRequisition: storesRequisition,
        ),
      ),
    ).then((v) {
      if (v != null) {
        if (storesRequisition == null) {
          // 新增时回到第一页
          tableKey.currentState?.pageTo(0);
        }
        _loadData();
      }
    });
  }

  _reset() {
    storesRequisition = StoresRequisition();
    formKey.currentState!.reset();
    _loadSelectVO();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await StoresRequisitionOdooApi.page(
        data: {"page": page, "domainList": storesRequisition.toDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _delete(List<StoresRequisition> selectedList) async {
    cryConfirm(context, S.of(context).confirmDelete, (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      var result = await StoresRequisitionOdooApi.removeByIds(ids);
      if (result.success!) {
        if(result.data["code"] != 200){
          CryUtils.message(result.data["message"]);
          return;
        }
        _query();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: StoresRequisitionDialog(),
      ),
    ).then((v) {
      if (v != null) {
        storesRequisition = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<StoresRequisition>((e) => StoresRequisition.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.add) {
          _edit(null);
        } else if (v == OperationType.edit) {
          _edit(selectedList[0]);
        } else if (v == OperationType.delete) {
          _delete(selectedList);
        } else if (v == OperationType.dmsFile) {
          _openDetail(selectedList[0]);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.add,
          child: ListTile(
            leading: const Icon(Icons.add),
            title: Text('添加'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.edit,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.edit),
            enabled: selectedList.length == 1,
            title: Text('修改'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.delete,
          enabled: selectedList.length != 0,
          child: ListTile(
            leading: const Icon(Icons.delete),
            enabled: selectedList.length != 0,
            title: Text('删除'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.dmsFile,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.view_agenda_rounded),
            enabled: selectedList.length == 1,
            title: Text('领料单明细'),
          ),
        ),
      ],
    );
  }
}
